<template>
  <div class="product-add">
    <div class="left">
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <span>新增商品</span>
          </div>
        </template>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="商品名称" prop="title">
            <el-input v-model="form.title" placeholder="请输入商品名称" />
          </el-form-item>

          <el-form-item label="商品分类" prop="categoryId">
            <el-select v-model="form.categoryId" filterable placeholder="请选择分类">
              <el-option v-for="c in categoryOptions" :key="c.id" :label="c.name" :value="c.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="商品价格" prop="price">
            <el-input-number v-model="form.price" :precision="2" :step="0.1" :min="0" placeholder="请输入价格" />
          </el-form-item>

          <el-form-item label="上架时间" prop="saleTime">
            <el-date-picker v-model="form.saleTime" type="datetime" placeholder="选择日期时间" value-format="x"
              format="YYYY-MM-DD HH:mm:ss"
              :disabled-date="(d: Date) => d.getTime() < Date.now() - 86400000 * 365 * 50" />
          </el-form-item>

          <el-form-item label="轮播图片" prop="bannerUrl">
            <FileUpload :allowed-types="['image/*']" :multiple="true" :max-size="5 * 1024 * 1024" v-model="bannerFiles"
              @success="onBannerSuccess" />
            <div class="tip">最多5张</div>
          </el-form-item>

          <el-form-item label="详情图" prop="infoUrl">
            <FileUpload :allowed-types="['image/*']" :multiple="true" :max-size="5 * 1024 * 1024" v-model="infoFiles"
              @success="onInfoSuccess" />
            <div class="tip">最多10张</div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :loading="submitting" @click="handleSubmit">提交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div class="right">
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <span>子商品 SKU</span>
            <el-button type="primary" size="small" @click="addSku">添加子商品</el-button>
          </div>
        </template>
        <div v-if="skus.length === 0" class="sku-empty">点击“添加子商品”创建子项</div>
        <div v-for="(sku, index) in skus" :key="sku.id" class="sku-item">
          <el-row :gutter="4" align="middle">
            <el-col :span="12">
              <el-input v-model="sku.attr" placeholder="子商品名称" />
            </el-col>
            <el-col :span="4">
              <FileUpload :allowed-types="['image/*']" :multiple="false" :max-size="5 * 1024 * 1024" :variant="'plain'"
                :show-file-list="false" :inline-preview="true" v-model="sku.fileList"
                @success="f => onSkuSuccess(index, f)" />
            </el-col>
            <el-col :span="4" class="sku-actions">
              <el-button type="danger" plain @click="removeSku(index)">删除</el-button>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import FileUpload from '@/components/FileUpload.vue'
import { addProduct } from '@/api/shop'

interface CategoryOption { id: number; name: string }

const categoryOptions = ref<CategoryOption[]>([
  { id: 1, name: '家用电器' },
  { id: 2, name: '手机数码' },
  { id: 3, name: '服饰箱包' },
])

interface ProductForm {
  title: string
  categoryId: number | null
  saleTime: string | number | null
  bannerUrl: string[]
  infoUrl: string[]
  price: number | null
}

const formRef = ref<FormInstance>()
const form = reactive<ProductForm>({
  title: '',
  categoryId: null,
  saleTime: null,
  bannerUrl: [],
  infoUrl: [],
  price: null,
})

// 与上传组件同步的文件列表（用于回显和删除）
const bannerFiles = ref<any[]>([])
const infoFiles = ref<any[]>([])

// 子商品SKU
interface SkuItem {
  id: string
  attr: string
  skuUrl: string | null
  fileList: any[]
}

const skus = ref<SkuItem[]>([])

const rules: FormRules = {
  title: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
  saleTime: [{ required: true, message: '请选择上架时间', trigger: 'change' }],
  bannerUrl: [{ validator: (_, __, cb) => (form.bannerUrl.length > 0 ? cb() : cb(new Error('请至少上传1张轮播图'))), trigger: 'change' }],
  price: [
    { required: true, message: '请输入价格', trigger: 'change' },
    { validator: (_, v, cb) => (v === null || v === undefined || v <= 0 ? cb(new Error('价格需大于0')) : cb()), trigger: 'change' }
  ],
}

const submitting = ref(false)

function onBannerSuccess(file: any) {
  if (file?.url) {
    if (form.bannerUrl.length >= 5) return
    form.bannerUrl = [...form.bannerUrl, file.url]
  }
}

function onInfoSuccess(file: any) {
  if (file?.url) {
    if (form.infoUrl.length >= 10) return
    form.infoUrl = [...form.infoUrl, file.url]
  }
}

function resetForm() {
  form.title = ''
  form.categoryId = null
  form.saleTime = null
  form.bannerUrl = []
  form.infoUrl = []
  form.price = null
  bannerFiles.value = []
  infoFiles.value = []
  skus.value = []
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      submitting.value = true
      const payload = {
        title: form.title,
        categoryId: form.categoryId,
        saleTime: Number(form.saleTime),
        bannerUrl: form.bannerUrl.slice(0, 5),
        infoUrl: form.infoUrl.slice(0, 10),
        price: Number(form.price),
        skus: skus.value.map(s => ({ attr: s.attr, skuUrl: s.skuUrl }))
      }
      await addProduct(payload)
      ElMessage.success('新增成功')
      resetForm()
    } catch (e) {
      // ignore - 统一拦截器已处理
    } finally {
      submitting.value = false
    }
  })
}

function addSku() {
  skus.value.push({ id: `${Date.now()}-${Math.random()}`, attr: '', skuUrl: null, fileList: [] })
}

function removeSku(index: number) {
  skus.value.splice(index, 1)
}

function onSkuSuccess(index: number, file: any) {
  const s = skus.value[index]
  if (!s) return
  s.skuUrl = file?.url || null
  if (s.fileList && s.fileList.length > 1) {
    s.fileList = [s.fileList[s.fileList.length - 1]]
  }
}
</script>

<style scoped>
.product-add {
  display: flex;
  gap: 16px;
  padding: 16px;
}

.left {
  flex: 0 0 50%;
}

.right {
  flex: 1 1 50%;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.tip {
  margin-left: 12px;
  color: #909399;
  font-size: 12px;
}
</style>
